<?php
/**
 * @package YARBB
 * @copyright Авторские права (C) 2009 www.yar-it.com. Все права защищены.
 * @license Лицензия http://www.gnu.org/licenses/gpl-2.0.htm GNU/GPL, или help/license.php
 * YARBB! - свободное программное обеспечение распространяемое по условиям лицензии GNU/GPL
 * Для получения информации о используемых расширениях и замечаний об авторском праве, смотрите файл copyright.php.
 */

// no direct access
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );
// Make sure no one attempts to run this script "directly"
if (!defined('YARBB'))
	exit;
//
// Validate an e-mail address
//
function is_valid_email($email) {
	if (strlen($email) > 50)
		return false;
	return preg_match('/^(([^<>()[\]\\.,;:\s@"\']+(\.[^<>()[\]\\.,;:\s@"\']+)*)|("[^"\']+"))@((\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\])|(([a-zA-Z\d\-]+\.)+[a-zA-Z]{2,}))$/', $email);
}
//
// Check if $email is banned
//
function is_banned_email($email) {
	global  $yarbb_bans;//s
	foreach ($yarbb_bans as $cur_ban) {
		if ($cur_ban['email'] != '' &&
				($email == $cur_ban['email'] ||
						(strpos($cur_ban['email'], '@') === false && stristr($email, '@'.$cur_ban['email']))))
			return true;
	}
	return false;
}
//
// Wrapper for PHP's mail()
//
function yarbb_mail($to, $subject, $message, $from = '') {
	global $yarbb_config;
	// Default sender/return address
	if (!$from)
		$from = '"'.str_replace('"', '', $yarbb_config['o_board_title'].' '._Y_YARROBOTMAIL).'" <'.$yarbb_config['o_webmaster_email'].'>';
	// Do a little spring cleaning
	$to = trim(preg_replace('#[\n\r]+#s', '', $to));
	$subject = trim(preg_replace('#[\n\r]+#s', '', $subject));
	$from = trim(preg_replace('#[\n\r:]+#s', '', $from));
	$headers = 'From: '.$from."\r\n".'Date: '.date('r')."\r\n".'MIME-Version: 1.0'."\r\n".'Content-transfer-encoding: 8bit'."\r\n".'Content-type: text/plain; charset='._ISO."\r\n".'X-Mailer: Agora Mailer';
	// Make sure all linebreaks are CRLF in message
	$message = str_replace("\n", "\r\n", yarbb_linebreaks($message));
	if ($yarbb_config['o_smtp_host'] != '')
		smtp_mail($to, $subject, $message, $headers);
	else {
		// Change the linebreaks used in the headers according to OS
		if (strtoupper(substr(PHP_OS, 0, 3)) == 'MAC')
			$headers = str_replace("\r\n", "\r", $headers);
		else if (strtoupper(substr(PHP_OS, 0, 3)) != 'WIN')
			$headers = str_replace("\r\n", "\n", $headers);
		mail($to, $subject, $message, $headers);
	}
}
//
// This function was originally a part of the phpBB Group forum software phpBB2 (http://www.phpbb.com).
// They deserve all the credit for writing it. I made small modifications for it to suit Agora and it's coding standards.
//
function server_parse($socket, $expected_response) {
	$server_response = '';
	while (substr($server_response, 3, 1) != ' ') {
		if (!($server_response = fgets($socket, 256)))
			mosRedirect(YARBB_URL, 'Couldn\'t get mail server response codes. Please contact the forum administrator.');
	}
	if (!(substr($server_response, 0, 3) == $expected_response))
		mosRedirect(YARBB_URL, 'Unable to send e-mail. Please contact the forum administrator with the following error message reported by the SMTP server: "'.$server_response.'"');
}
//
// This function was originally a part of the phpBB Group forum software phpBB2 (http://www.phpbb.com).
// They deserve all the credit for writing it. I made small modifications for it to suit PunBB and it's coding standards.
//
function smtp_mail($to, $subject, $message, $headers = '') {
	global $yarbb_config;
	$recipients = explode(',', $to);
	// Are we using port 25 or a custom port?
	if (strpos($yarbb_config['o_smtp_host'], ':') !== false)
		list($smtp_host, $smtp_port) = explode(':', $yarbb_config['o_smtp_host']);
	else {
		$smtp_host = $yarbb_config['o_smtp_host'];
		$smtp_port = 25;
	}
	if (!($socket = fsockopen($smtp_host, $smtp_port, $errno, $errstr, 15)))
		mosRedirect(YARBB_URL, 'Could not connect to smtp host "'.$yarbb_config['o_smtp_host'].'" ('.$errno.') ('.$errstr.')');
	server_parse($socket, '220');
	if ($yarbb_config['o_smtp_user'] != '' && $yarbb_config['o_smtp_pass'] != '') {
		fwrite($socket, 'EHLO '.$smtp_host."\r\n");
		server_parse($socket, '250');
		fwrite($socket, 'AUTH LOGIN'."\r\n");
		server_parse($socket, '334');
		fwrite($socket, base64_encode($yarbb_config['o_smtp_user'])."\r\n");
		server_parse($socket, '334');
		fwrite($socket, base64_encode($yarbb_config['o_smtp_pass'])."\r\n");
		server_parse($socket, '235');
	}
	else {
		fwrite($socket, 'HELO '.$smtp_host."\r\n");
		server_parse($socket, '250');
	}
	fwrite($socket, 'MAIL FROM: <'.$yarbb_config['o_webmaster_email'].'>'."\r\n");
	server_parse($socket, '250');
	$to_header = 'To: ';
	@reset($recipients);
	while (list(, $email) = @each($recipients)) {
		fwrite($socket, 'RCPT TO: <'.$email.'>'."\r\n");
		server_parse($socket, '250');
		$to_header .= '<'.$email.'>, ';
	}
	fwrite($socket, 'DATA'."\r\n");
	server_parse($socket, '354');
	fwrite($socket, 'Subject: '.$subject."\r\n".$to_header."\r\n".$headers."\r\n\r\n".$message."\r\n");
	fwrite($socket, '.'."\r\n");
	server_parse($socket, '250');
	fwrite($socket, 'QUIT'."\r\n");
	fclose($socket);
	return true;
}